package com.bckj.fastboot.core.util;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.InvocationHandlerAdapter;
import net.bytebuddy.matcher.ElementMatchers;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;

@SuppressWarnings("unchecked")
public class ByteBuddyProxyFactory {

    public static <T> T createProxy(Class<T> interfaceClass, InvocationHandler handler) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        try (DynamicType.Unloaded<Object> unloaded = new ByteBuddy()
                .subclass(Object.class)
                .implement(interfaceClass)
                .method(ElementMatchers.nameMatches("^process.*"))
                .intercept(InvocationHandlerAdapter.of(handler)) // 委托给自定义处理类
                .make()) {
            return (T)
                    unloaded.load(interfaceClass.getClassLoader())
                            .getLoaded()
                            .getDeclaredConstructor()
                            .newInstance();
        }
    }
}